package cn.tedu.boot11.controller;

import cn.tedu.boot11.entity.User;
import cn.tedu.boot11.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {

    @RequestMapping("/user/reg")
    @ResponseBody
    public String reg(User user){
        try(Connection conn= DBUtils.getConn()){
            String sql="select id from user where username=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs=ps.executeQuery();
            if (rs.next()){
                System.out.println("该用户已存在!");
            }else {
                String insertSql="insert into user values(null,?,?,?)";
                PreparedStatement insertPs=conn.prepareStatement(insertSql);
                insertPs.setString(1,user.getUsername());
                insertPs.setString(2,user.getPassword());
                insertPs.setString(3,user.getNick());
                insertPs.executeUpdate();
                System.out.println("注册成功!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        System.out.println("user = " + user);

        return "注册成功!";
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public String login(User user){
        try (Connection conn=DBUtils.getConn()){
            String sql="select password from user where username=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs=ps.executeQuery();
            if (rs.next()){
                String pw=rs.getString(1);//得到数据库里面的密码
                if (user.getPassword().equals(pw)){
                    return "登录成功!";
                }else {
                    return "密码错误!";
                }
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        System.out.println("user = " + user);
        return "该用户不存在!";
    }
}
















